package com.fwj.auth.config.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fwj.auth.api.user.UserService;
import com.fwj.auth.entity.user.UserBaseInfo;
import com.fwj.auth.model.AuthUser;
import com.fwj.auth.model.UserVo;
import com.fwj.core.common.common.CommonUtils;
import com.fwj.core.common.common.CookieUtil;
import com.fwj.core.common.common.RedisUtil;
import com.fwj.core.common.common.StringGeneratorUtil;
import com.fwj.core.common.constant.UserConstant;
import com.fwj.core.common.execption.CommonException;
import com.fwj.core.common.model.ResponseDTO;
import com.fwj.core.common.model.ResponseEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: fwj
 * @Data: 2022/2/20 21:22
 * @Version 1.0
 * @Description:
 */

@Component
public class AuthLoginSuccessHandler implements AuthenticationSuccessHandler {

    //添加日志工厂
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthLoginSuccessHandler.class);

    private static UserService userService;
    @Resource
    public void setUserRoleMapper(UserService userService) {
        AuthLoginSuccessHandler.userService = userService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
        //查找用户基本信息
        UserBaseInfo userBaseInfo = userService.findUserByAccount(authentication.getName());
        if (CommonUtils.isEmpty(userBaseInfo)){  throw new CommonException(ResponseEnum.USER_NO_EXISTS); }
        if (userBaseInfo.getStatus().equals(UserConstant.FROZEN)){  throw new CommonException(ResponseEnum.USER_NO_EXISTS); }
        String authSession = StringGeneratorUtil.randomSequence(32);
        //添加会话到Cookie
        CookieUtil.addCookie(resp,"localhost", "/", "authSession", authSession,
                60*60*4, true);
        //存储用户数据到Redis
        String jsonUser = JSONObject.toJSONString(userBaseInfo);
        AuthUser authUser = JSON.parseObject(jsonUser,AuthUser.class);
        RedisUtil.setTimeOut(authSession,JSONObject.toJSONString(authUser),60*60*4);
        //返回数据
        UserVo retUserVo = getUserVo(userBaseInfo);
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.success().setData(retUserVo);
        ResponseUtil.response(resp, responseDTO);
    }

    private UserVo getUserVo(UserBaseInfo userBaseInfo){
        UserVo userVo = JSONObject.parseObject(JSON.toJSONString(userBaseInfo),UserVo.class);
        return userVo;
    }

}
